<?php
$arr_extension=array
(
	'.gif'=>'.gif',
	'.jpg'=>'.jpg',
	'.jpeg'=>'.jpeg',
	'.png'=>'.png'
);

define('VS_XORCODE',1);

function isGod()
{
	global $_SESSION;
	if ( @$_SESSION['sesgod'] != 0 )	return true;
	else return false;
}

/*
Kiểm tra trạng thái administrator đã login hay chưa (chỉ dùng cho quản lý)
*/
function isLogin()
{
	global $_SESSION;
	if ( @$_SESSION['seslogin'] == true )	return true;
	else	return false;
}
/* 
Kiểm tra quyền truy cập từng module đối với username đang truy cập
*/
function getRights($modName,$right)
{
	global $link,$_SESSION;
	$sql = "select * from gaccess where modname='$modName' and gid=" . $_SESSION['sesgid'];
	$rs = $link->execute($sql);
	if ( !$rs->EOF )
		switch ( strtolower($right) )
		{
			case 'view':
				return $rs->fields('view');	break;
			case 'add':
				return $rs->fields('add');	break;
			case 'edit':
				return $rs->fields('edit');	break;
			case 'delete':
				return $rs->fields('delete');	break;
			case 'search':
				return $rs->fields('search');	break;
			case 'full':
				$r = intval(($rs->fields('view') + $rs->fields('add') + $rs->fields('edit') + $rs->fields('delete') + $rs->fields('search'))/4);
				return $r;	
				break;
		}
	else
		return 0;
}
/* Chuyển từ VNDate sang MySQL Date */
function toMYSQLDate($dt)
{
	return substr($dt,6,4) . '-' . substr($dt,3,2) . '-' . substr($dt,0,2);
}

function return_bytes($val)
{
	$val=trim($val);
	$last=strtolower($val{strlen($val)-1});
	switch($last)
		{
		case "g":
			$val*=1024;
		case "m":
			$val*=1024;
		case "k":
			$val*=1024;	
	}
	return $val;
}
/*
Sử dụng Image database
*/
function InsertImgToDB($path, $file)
{
	global $link;

	$handle = fopen($path . $file,'r');
	$file_content = fread($handle,filesize($path . $file));
	fclose($handle);
	$encoded = chunk_split(base64_encode($file_content)); 

	$sql = "INSERT INTO images(sixfourdata) VALUES('$encoded')"; 
	$link->execute($sql);

	$sql = "SELECT MAX(imgid) as maxid FROM images";
	$rs = $link->execute($sql);

	return $rs->fields('maxid');
}

function BannerAdmin($txt='',$echo = true)
{
	$str = '';
	$str .= '<table cellpadding="0" cellspacing="0" border="0" width="100%" align="center" style="border: 2px outset;color: #FFFFFF;">';
	$str .= '<tr><td height="27" bgcolor="#336699" style=" font-weight: bold"> <img src="images/Button.gif" border="0" align="absmiddle">&nbsp;<font color="#FFFF00">HỆ THỐNG QUẢN LÝ </font>.::. ' . $txt . '</td>';
	$str .= '<td align="right" bgcolor="#336699" style=" font-weight: bold; cursor:hand" ><a href="javascript:history.back(-1)" style="color: #FFFFFF; font-weight:bold; text-decoration:none; cursor: hand"><img src="images/back.gif" border="0" align="absmiddle" alt="Trang truoc">&nbsp;Trang trước</a>&nbsp;</a></td>';
	$str .= '</tr>';
	$str .= '</table>';
	
	if ( $echo )	echo $str;
	else			return $str;
}

function blockRender($side='l',$visible=1)
{
	global $link, $info, $template, $lang;
	$sql = "SELECT * FROM block WHERE side='$side' AND visible=$visible ORDER BY weight DESC";
	$rsb = $link->execute($sql);
	while ( !$rsb->EOF )
	{
		$bfile = $info['block_path'] . $rsb->fields('id') . '.php';
		if ( file_exists($bfile) )
		{
			include($bfile);
			if ( !isset($ignore) )
			{
				$template->set_filenames(array('block'=>'block.tpl'));
				$template->assign_vars(array(
					'_BLOCKTITLE'=>$_blockTitle,
					'_BLOCKCONTENT'=>$_blockContent
				));
				$template->pparse('block');
			}
		}
		$rsb->MoveNext();
	}
}

function headerSD($txt,$clr='',$isupper='')
{
	global $info;
	$str = '';
	$upper = '';
	if ( !empty($isupper) )
		$upper = "text-transform: uppercase;";
	if ( empty($clr) )
		$str .= '<div style="height: 21; border-bottom: 1px solid #336699;"><img src="' . $info['template_image_path']. 'news.gif" border="0" align="absmiddle" style="position: fixed; float: left;"><span style="font-weight:bold; color: #000066;' . $upper . 'FILTER: dropShadow(color=#AAAAAA, offX=1, offY=1, positive=1);width:100%;height: 100%;">' . $txt . '</span></div>';
	else
		$str .= '<div style="height: 21; border-bottom: 1px solid #336699;"><img src="' . $info['template_image_path'] . 'news.gif" border="0" align="absmiddle" style="position: fixed; float: left;"><span style="font-weight:bold; color: ' . $clr . ';' . $upper . 'FILTER: dropShadow(color=#AAAAAA, offX=1, offY=1, positive=1);width:100%;height: 100%;">' . $txt . '</span></div>';
	return $str;
}

function newLine($n=1) { for ( $i=0; $i<$n; $i++ ) { echo '<br />'; } }

function setURLParams($params)
{
	$params = syncString($params);
	$params = base64_encode($params);
	$temp = '';
	for ( $i=0; $i<strlen($params); $i+=5 )
		$temp .= substr($params,$i,5) . "_";
	return substr($temp,0,strlen($temp)-1);
}

function getURLParams($params)
{
	$var = str_replace("_","",$params);
	$var = base64_decode($var);
	$var = syncString($var);
	$var = split('&',$var);
	$temp = array();

	while ( list($key,$val) = each($var) )
	{
		$temp1 = split('=',$val);
		@$temp[$temp1[0]] = $temp1[1];
	}
	return $temp;
}

/********************************************************************************************/
function GetPages( $rs, $page_size, $record_count = -1 )
{
	if ( $record_count == -1 )
	{
		if ( $rs->RecordCount() % $page_size != 0 )
			return (int)($rs->RecordCount()/$page_size) + 1;
		else
			return (int)($rs->RecordCount()/$page_size);
	}
	else
	{
		if ( $record_count % $page_size != 0 )
			return (int)($record_count/$page_size) + 1;
		else
			return (int)($record_count/$page_size);		
	}
}

/*********************************************************************************************
function:
	Paging
Params:
	$rs: recordset (is instance of adodb_lite (or adodb))
	$page_size: num record to show in each page
	$list_page_name: name of file list data from recordset
	$current_page: current page to show
	$numofpageshow: num pages in nave bar
	$next_prev: =true/false to show next/prev button
	$shownavnum: =true if not show input filed, =false if show input filed
	$brd: =true if nav bar has border
	$is_top: =true if nav bar show in top list; =false if nav bar show in bottom list
	$record_count: =-1 if using recordset for pageing, =<num> if using num for paging
*********************************************************************************************/
function ShowPaging($rs, $page_size, $list_page_name, $current_page, $numofpageshow=5, $next_prev=false, $shownavnum=true, $brd=true, $is_top=true, $record_count = -1)
{
	$str = "<script language=\"javascript\">";
	$str .= "function ChangePage(newPage){ window.location = newPage;}";
	$str .= "</script>";
	if ( $record_count == -1 )
	{
		$n = GetPages($rs, $page_size);
		$trecord = $rs->recordcount();
	}
	else
	{
		$n = GetPages($rs, $page_size, $record_count);
		$trecord = $record_count;
	}
	if ( $n > $numofpageshow )
		$shownavnum = false;
		
	if ( $brd == true )
		$str .= "<table width='' cellpadding='2' cellspacing='1' border='0' style='border: 1px solid #336699'>";
	else		
		$str .= "<table width='' cellpadding='2' cellspacing='1' border='0'>";
	$str .= " <tr>";
	$str .= "  <td style='font-family:Tahoma,Verdana,Arial; font-size:11px'>Có tất cả <font color=\"#FF0000\">" . $n . "</font> trang (<span style='color: #FF0000'>" . $trecord . "</span> mẫu tin)</td>";
	
	if ( $current_page >= $n ) $current_page = $n;
	
	if ( $current_page == 0 ) $current_page = 1;
	
	//Prev and move first button
	if ( $next_prev == true )
	{
		if ( $current_page >=2 ) {
			$str .= "<td bgcolor=\"#336699\" style=\"cursor: hand; font-family:Tahoma,Verdana,Arial; font-size:11px;color:#FFFFFF\" onClick=\"ChangePage('" . $list_page_name . "&page=1')\"> |« </td>";
			$str .= "<td bgcolor=\"#009900\" style=\"cursor: hand; font-family:Tahoma,Verdana,Arial; font-size:11px;color:#FFFFFF\" onClick=\"ChangePage('" . $list_page_name . "&page=" . ($current_page-1) . "')\"> « </td>";
		}
		else {
			$str .= "<td bgcolor='#CCCCCC' style='font-family:Tahoma,Verdana,Arial; font-size:11px;color:#FFFFFF'> |« </td>";
			$str .= "<td bgcolor=\"#CCCCCC\" style=\"font-family:Tahoma,Verdana,Arial; font-size:11px;color:#FFFFFF\"> « </td>";
		}
	}
	
	//Nav num button
	if ( $shownavnum == true ) {
		if ( $n <= $numofpageshow )
			for ( $i=1 ; $i <= $n; $i++ )
			{
				if ( $i == $current_page )
					$str .= "<td bgcolor='#336699' style='font-family:Tahoma,Verdana,Arial; font-size:11px;color:#FFFFFF'>" . $i . "</td>";
				else
					$str .= "<td style=\"cursor:hand;Tahoma,Verdana,Arial; font-size:11px\" onClick=\"ChangePage('" . $list_page_name . "&page=" . $i . "');\">" . $i . "</td>";
			}
		else
		{
			$half = (int)(($numofpageshow-1)/2); //=1
			if ( $half == 0 ) $half = 1;

			if ( $current_page < $n && $current_page > 1 )
			{		
				$start_pos = $current_page-$half;
				$end_pos = $current_page+$half;

				if ( $numofpageshow % 2 == 0 )
					$end_pos += 1;
				
				if ( $start_pos <= 0 ) { $start_pos = 1; $end_pos += 1; }
				if ( $end_pos > $n ) { $start_pos -= 1; $end_pos = $n; }
				
				for ( $i = $start_pos ; $i <= $end_pos; $i++ )
					if ( $i == $current_page )
						$str .= "<td bgcolor='#336699' style='font-family:Tahoma,Verdana,Arial; font-size:11px;color:#FFFFFF'>" . $i . "</td>";
					else
						$str .= "<td style=\"cursor:hand;Tahoma,Verdana,Arial; font-size:11px\" onClick=\"ChangePage('" . $list_page_name . "&page=" . $i . "');\">" . $i . "</td>";
			}
			else if ( $current_page >= $n )
				for ( $i = $n-$numofpageshow+1 ; $i <= $n; $i++ )
					if ( $i == $current_page )
						$str .= "<td bgcolor='#336699' style='font-family:Tahoma,Verdana,Arial; font-size:11px;color:#FFFFFF'>" . $i . "</td>";
					else
						$str .= "<td style=\"cursor:hand;Tahoma,Verdana,Arial; font-size:11px\" onClick=\"ChangePage('" . $list_page_name . "&page=" . $i . "');\">" . $i . "</td>";
			else if ( $current_page <= 1 )					
				for ( $i = 1 ; $i <= $numofpageshow; $i++ )
					if ( $i == $current_page )
						$str .= "<td bgcolor='#336699' style='font-family:Tahoma,Verdana,Arial; font-size:11px;color:#FFFFFF'>" . $i . "</td>";
					else
						$str .= "<td style=\"cursor:hand;Tahoma,Verdana,Arial; font-size:11px\" onClick=\"ChangePage('" . $list_page_name . "&page=" . $i . "');\">" . $i . "</td>";
		}
	}
	else {	//show input nav field
		$str .= "<td align=\"center\" bgcolor=\"#F5F5F5\" style=\"padding: 0 0 0 0\">";
		$str .= "<input type=\"text\" name=\"txt_pages\" value=\"" . $current_page . "\" size=\"1\" maxlength=\"4\" onKeyDown=\"DKMH_doKeyPress();\" style=\"border: 1px solid #336699;\">";
		$str .= "</td>";
		$str .= "<script language='javascript'>";
		$str .= "	function DKMH_doKeyPress() {";
		$str .= "		var dkmh_pages = parseInt(document.all['txt_pages'].value);";		
		$str .= "		if ( event.keyCode == 13 ) {";
		$str .= "			document.all['txt_pages'].blur();";
		$str .= "			ChangePage('" . $list_page_name . "&page=' + dkmh_pages);";
		$str .= "		}";
		$str .= "	}";
		$str .= "</script>";		
	}
	
	//Next and move last button
	if ( $next_prev == true )
	{
		if ( $current_page <= ($n-1) ) {
			$str .= "<td bgcolor=\"#009900\" style=\"cursor: hand; font-family:Tahoma,Verdana,Arial; font-size:11px;color:#FFFFFF\" onClick=\"ChangePage('" . $list_page_name . "&page=" . ($current_page+1) . "')\"> » </td>";
			$str .= "<td bgcolor=\"#336699\" style=\"cursor: hand; font-family:Tahoma,Verdana,Arial; font-size:11px;color:#FFFFFF\" onClick=\"ChangePage('" . $list_page_name . "&page=" . $n . "')\"> »| </td>";
		}
		else {
			$str .= "<td bgcolor=\"#CCCCCC\" style=\"font-family:Tahoma,Verdana,Arial; font-size:11px;color:#FFFFFF\"> » </td>";
			$str .= "<td bgcolor='#CCCCCC' style='font-family:Tahoma,Verdana,Arial; font-size:11px;color:#FFFFFF'> »| </td>";
		}
	}
	
	$str .= " </tr>";
	$str .= "</table>";
	
	if ( $is_top == true && $record_count == -1 )
		$rs->Move(($current_page-1)*$page_size);
	return $str;
}

//################# ONLY FOX #########################
function changeFontEncoding($txt,$arr,$inv=false) {
	//die('fdfd');
	if ( !$inv )
		while (list($key, $val) = each($arr)) {
			$txt = str_replace($key,$val,$txt);
		}
	else
		while (list($key, $val) = each($arr)) {
			$txt = str_replace($val,$key,$txt);
		}	
	return $txt;
}

function toVNDate($dt)
{
	$temp = substr($dt,8,2) . "/" . substr($dt,5,2) . "/" . substr($dt,0,4);
	if ( $temp == "01/01/1970" )	
		return "-";
	else if ( $temp == '00/00/0000' )
		return '';
	else
		return $temp; 
}

function getVar($name,$isNum=false,$post=false)
{
	global $_POST,$_GET;
	if ( $post == false )
		if ( $isNum == true )
			return trim((!get_magic_quotes_gpc()) ? addslashes(@$_GET[$name]) : intval(@$_GET[$name]));
		else
			return trim((!get_magic_quotes_gpc()) ? addslashes(@$_GET[$name]) : @$_GET[$name]);
	else
		if ( $isNum == true )
			return trim((!get_magic_quotes_gpc()) ? addslashes(@$_POST[$name]) : intval(@$_POST[$name]));
		else
			return trim((!get_magic_quotes_gpc()) ? addslashes(@$_POST[$name]) : @$_POST[$name]);
		
}

function removeSQLInjection($txt)
{
	//if ( !get_magic_quotes_gpc() ) 
		return trim(addslashes($txt));
	//else
		//return trim($txt);
}

function gen_rand_string($hash)
{
	$chars = array( 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'j', 'J',  'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'o', 'O', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T',  'u', 'U', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
	
	$max_chars = count($chars) - 1;
	srand( (double) microtime()*1000000);
	
	$rand_str = '';
	for($i = 0; $i < 8; $i++)
	{
		$rand_str = ( $i == 0 ) ? $chars[rand(0, $max_chars)] : $rand_str . $chars[rand(0, $max_chars)];
	}

	return ( $hash ) ? md5($rand_str) : $rand_str;
}

function vsmax($var1,$var2)
{
	$var1 = floatval(trim($var1));
	$var2 = floatval(trim($var2));
	
	//echo 'vsmax :: var1=' . $var1 . " :: var2=" . $var2 . '<br />';
	
	if ( $var1 >= $var2 )	return $var1;
	else return $var2;
}
/* Kiểm tra module có đang ở trạng thái kích họat hay không ? */
function getModEnabled($mname)
{
	global $link;
	$sql = "select * from um_module where modname='$mname'";
	$rs = $link->execute($sql);
	if ( !$rs->EOF )
		if ( $rs->fields('enabled') != 0 )
			return true;
		else
			return false;
	else
		return false;
}

function showMsg($msg,$icon='',$al='left')
{
	global $template;
	$template->set_filenames(array(
		'msg' => 'message.tpl'
	));
	
	if ( !empty($icon) )
		$template->assign_vars(array(
			'_RS_ICON' => '<img src="images/' . $icon . '.gif" bordr="0" align="absmiddle">'
		));
	else
		$template->assign_vars(array(
			'_RS_ICON' => ''
		));
	$template->assign_vars(array(
		'_RS_MSG'   => $msg,
		'_RS_ALIGN' => $al
	));
		
	$template->pparse('msg');
}

function syncString($s)
{
	$str = '';
	while ( strlen($s) > 0 )
	{
		$t = ord(substr($s,0,1));
		$t = $t ^ VS_XORCODE | VS_XORCODE >> VS_XORCODE;
		$str .= chr($t);
		$s = substr($s,1,strlen($s)) ;
	}
	return $str;
}

//tao so sercurity code
function genRCode($rnd,$sitekey='',$datekey='')
{
	global $info;
	$arrChar = array('A','x','m','f','P','t');
	
	if ( empty($sitekey) )	$sitekey = $info['sitekey'];
	if ( empty($datekey) )	$datekey = date("F j");
	
	$str = '';
	
	$rcode = hexdec(md5($_SERVER['HTTP_USER_AGENT'] . $sitekey . $rnd . $datekey));
	$rcode = substr($rcode, 2, 6);
	
	for ( $i=0; $i < strlen($rcode); $i++ )
	{
		if ( substr($rcode,$i,1) > 4 )
			$str .= $i;
		else
			$str .= $arrChar[substr($rcode,$i,1)];
	}
	$str = str_replace('0','Y',$str);
	return $str;
}

function genRnd()
{
	mt_srand ((double)microtime()*1000000);
	$maxran = 1000000;
	return mt_rand(0, $maxran);
}

function addPoint($so)
{
	$so = trim($so);
	$solan_3so = strlen($so)/3;
	$sole = strlen($so)%3;
	$ketqua = "";
	
	if ( $sole != 0 )
	{
		$ketqua = substr($so,0,$sole);
		$so = substr($so,$sole,strlen($so));
	}
	for ( $i=0; $i<$solan_3so; $i++ )
		$ketqua .= "." . substr($so,$i*3,3);
	
	if ( $sole != 0 )
		return substr($ketqua,0,strlen($ketqua)-1);
	else
		return substr($ketqua,1,strlen($ketqua)-1);
}

function UnixDate2VNDate($dt)
{
	return date("d/m/Y",$dt);
}

/* Kiểm tra quyền của user với module */
function getPermission($mod)
{
	global $link, $_SESSION;
	$sql = "select mod_files.* from mod_files inner join um_user_access_mod_files on mod_files.fid=um_user_access_mod_files.file_id where um_user_access_mod_files.username='" . $_SESSION['sesusername'] . "' and mod_files.modname='$mod'";
	$rs = $link->execute($sql);
	if ( $rs->EOF )	return false;
	else	return true;
}

function getAccessFile($fn,$mod='News')
{
	global $link, $_SESSION;
	$sql = "select mod_files.* from mod_files inner join um_user_access_mod_files on mod_files.fid=um_user_access_mod_files.file_id where um_user_access_mod_files.username='" . $_SESSION['sesusername'] . "' and mod_files.fname='$fn' and mod_files.modname='$mod'";
	//echo'sql=' . $sql . '<br />';
	$rs = $link->execute($sql);
	//echo '--> record count:' . $rs->recordcount();
	if ( $rs->EOF )	return false;
	else	return true;
}

function showHeader($txt)
{
	$str = '
		<table border="0" cellpadding="0" cellspacing="0" align="center" width="100%">
			<tr> 
			  <td height="45" align="right" valign="top" class="vspageheaderright" style="text-transform:uppercase">' . $txt . '</td>
			</tr>
			<tr><td>&nbsp;</td><tr>
		</table>	
	';
	return $str;
}

function session_pagestart($session_id)
{
	global $link;
	global $_COOKIE, $_GET, $SID;
	
	include('4rum/config.php');
	
	/* doc tham so config cua 4rum */
	$board_config = array();
	$sql = "SELECT * FROM cms_config";
	$rs = $link->Execute($sql);
	while ( !$rs->EOF )
	{
		$board_config[$rs->fields[0]] = $rs->fields[1];
		$rs->MoveNext();
	}
	
	$cookiename = $board_config['cookie_name'];

	/* doc bang session */
	$sql = "SELECT * FROM " . $table_prefix . "sessions WHERE session_id='$session_id'";
	//echo $sql;
	$rs = $link->Execute($sql);
	$userid = $rs->fields('session_user_id');
	$sql = "SELECT * FROM " . $table_prefix . "users WHERE user_id=$userid";
	$rs = $link->Execute($sql);
	$userdata = $rs->GetArray();
	
	return $userdata;
}

?>
